
import 'dart:convert';
import 'dart:io';
import 'package:bt_tool/basic/bt_http.dart';
import 'package:bt_tool/basic/bt_json_tool.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter_demo/tools/translate/translate_define.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:http/http.dart' as http;

class TranslateTool {



  static Future<BTHttpResultItem> translate(String sourceText,String target,String fromTarget) async {

    if(fromTarget == "zhCN" || fromTarget == "zh-CN"){
      fromTarget = "zh";
    }

    if(target == "zhCN" || target == "zh-CN"){
      target = "zh";
    }

    // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
    // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性
    // 以下代码示例仅供参考，建议采用更安全的方式来使用密钥
    // 请参见：https://cloud.tencent.com/document/product/1278/85305
    // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
    final tencentSecretId = "AKIDVs1ylJdjb6Zr0xjHh6PVRCuU0Y5a3Pba";
    final tencentSecretKey = "sY0LYaP5lRt89zhEY4Ut9HIH6rolgbhe";
    final token = '';

    final service = 'tmt';
    final host = 'tmt.tencentcloudapi.com';
    final endpoint = 'https://$host';
    final region = 'ap-beijing';
    final action = 'TextTranslate';
    final version = '2018-03-21';
    final algorithm = 'TC3-HMAC-SHA256';
    final timestamp = (DateTime.now().millisecondsSinceEpoch / 1000).toInt();
    final date = DateFormat('yyyy-MM-dd').format(DateTime.fromMillisecondsSinceEpoch(timestamp * 1000, isUtc: true));

    // ************* 步骤 1：拼接规范请求串 *************
    final httpRequestMethod = 'POST';
    final canonicalUri = '/';
    final canonicalQuerystring = '';
    final ct = 'application/json; charset=utf-8';
    final payload = "{\"SourceText\":\"$sourceText\",\"Source\":\"$fromTarget\",\"Target\":\"$target\",\"ProjectId\":0}";
    final canonicalHeaders = 'content-type:$ct\nhost:$host\nx-tc-action:${action.toLowerCase()}\n';
    final signedHeaders = 'content-type;host;x-tc-action';
    final hashedRequestPayload = sha256.convert(utf8.encode(payload));
    final canonicalRequest = '''$httpRequestMethod
$canonicalUri
$canonicalQuerystring
$canonicalHeaders
$signedHeaders
$hashedRequestPayload''';
    // print(canonicalRequest);

    // ************* 步骤 2：拼接待签名字符串 *************
    final credentialScope = '$date/$service/tc3_request';
    final hashedCanonicalRequest = sha256.convert(utf8.encode(canonicalRequest));
    final stringToSign = '''
$algorithm
$timestamp
$credentialScope
$hashedCanonicalRequest''';
    // print(stringToSign);

    // ************* 步骤 3：计算签名 *************
    List<int> sign(List<int> key, String msg) {
      final hmacSha256 = Hmac(sha256, key);
      return hmacSha256.convert(utf8.encode(msg)).bytes;
    }

    final secretDate = sign(utf8.encode('TC3$tencentSecretKey'), date);
    final secretService = sign(secretDate, service);
    final secretSigning = sign(secretService, 'tc3_request');
    final signature = Hmac(sha256, secretSigning).convert(utf8.encode(stringToSign)).toString();
    // print(signature);

    // ************* 步骤 4：拼接 Authorization *************
    final authorization = '$algorithm Credential=$tencentSecretId/$credentialScope, SignedHeaders=$signedHeaders, Signature=$signature';
    // print(authorization);

    // ************* 步骤 5：构造并发起请求 *************
    try{
      final response = await http.post(
        Uri.parse(endpoint),
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
          'Authorization': authorization,
          'X-TC-Action': action,
          'X-TC-Version': version,
          'X-TC-Region': region,
          'X-TC-Timestamp': timestamp.toString(),
          'X-TC-Token': token.toString(),
        },
        body: payload,
      );
      String jsonStr = utf8.decode(response.bodyBytes);
      var map = BTJsonTool.convertStrToMap(jsonStr);
      return BTHttpResultItem.success(null, BTHttpBusinessResultItem.success("suc", 1, map, map, null, 0, jsonStr));
    }catch(e){
      return BTHttpResultItem.fail(null,msg: e.toString());
    }
  }

  List<String> translateTargetList(){
    return TranslateDefine.baseLanguageMap.keys.toList();
  }
}